package org.dtrd.modules.quartz.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.util.DateUtils;
import org.dtrd.config.system.Constant;
import org.dtrd.modules.flup.entity.po.DtrdEntRdFlupAppointmentRecord;
import org.dtrd.modules.flup.service.IDtrdEntRdFlupAppointmentRecordService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 更新患者的复诊状态
 * @author qr
 * @date 2021/12/24 17:40
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Component
@Slf4j
public class FlupStatusJob implements Job {

    @Autowired
    private IDtrdEntRdFlupAppointmentRecordService appointmentRecordService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 查询状态为已预约的患者
        LambdaQueryWrapper<DtrdEntRdFlupAppointmentRecord> queryWrapper = Wrappers.lambdaQuery(DtrdEntRdFlupAppointmentRecord.class)
                .eq(DtrdEntRdFlupAppointmentRecord::getFlupStatus, Constant.FlupStatus.HasAppointment.getStatus());
        List<DtrdEntRdFlupAppointmentRecord> records = appointmentRecordService.list(queryWrapper);
        for (DtrdEntRdFlupAppointmentRecord record : records) {
            if (DateUtils.isToday(record.getFlupDate())) {
                Integer oldStatus = record.getFlupStatus();
                Constant.FlupStatus newStatus = Constant.FlupStatus.WaitToVisit;
                record.setFlupStatus(newStatus.getStatus());
                log.info("FlupStatusJob.execute: 更新患者复诊状态，patientId:{}, {}->{}",
                        record.getPatientId(),
                        Constant.FlupStatus.valueOf(oldStatus).getName(),
                        newStatus.getName());
            }
        }
        appointmentRecordService.updateBatchById(records);
    }
}
